from django.http import JsonResponse, HttpResponse
from django.shortcuts import render
from django.views import View
import json
from .models import Overtime
import datetime
from staff_management.models import Employee
from divisional_management.models import Department
from django.utils import timezone


# Create your views here.
# Overtime.creationTime.tzinfo = EST

# get请求时获取表格数据
def get_attendance():
    year = datetime.datetime.now().year
    month = datetime.datetime.now().month
    day = datetime.datetime.now().day
    atts = Overtime.objects.filter(start_time__gt=datetime.date(year, month, day))
    att_list = []
    for att in atts:
        emp_id = att.emp_id.emp_id
        name = att.emp_id.name
        dep = att.emp_id.dep_id.dep_name
        start_time = att.start_time
        end_time = att.end_time
        state = att.state
        att_dict = {}
        att_dict['emp_id'] = emp_id
        att_dict['name'] = name
        att_dict['dep'] = dep
        att_dict['start_time'] = start_time.strftime('%Y-%m-%d %H:%M:%S')
        att_dict['end_time'] = end_time.strftime('%Y-%m-%d %H:%M:%S')
        att_dict['state'] = state
        att_list.append(att_dict)
    return att_list

# 计算时间的方法
def time_data(year,month,day,before):
    month = month - 1
    if month in [1, 3, 5, 7, 8, 10, 12]:
        day = 31 + day - before
    elif month == 2:
        day = 29 + day - before if year % 400 == 0 or year % 4 == 0 and year % 100 != 0 else 28 + day - before
    else:
        day = 30 + day - before
    return month,day

# 计算显示多少号之前数据
def time_calculate(time):
    year = timezone.now().year
    month = timezone.now().month
    day = timezone.now().day
    if month==1 :
        if time == "今天":
            day = day
        elif time == "昨天":
            before = 1
            if day - 1 <= 0:
                year=year-1
                t_tuple = time_data(year, month, day, before)
                month = t_tuple[0]
                day = t_tuple[1]
            else:
                day = day - 1

        elif time == "三天前":
            before = 3
            if day - 3 <= 0:
                year = year - 1
                t_tuple = time_data(year, month, day, before)
                month = t_tuple[0]
                day = t_tuple[1]
            else:
                day = day - 3

        elif time == "七天前":
            before = 7
            if day - 7 <= 0:
                year = year - 1
                t_tuple = time_data(year, month, day, before)
                month = t_tuple[0]
                day = t_tuple[1]
            else:
                day = day - 7
        elif time == "本月":
            day = 1
    else:
        if time == "今天":
            day = day
        elif time == "昨天":
            before = 1
            if day - 1 <= 0:
               t_tuple=time_data(year,month,day,before)
               month=t_tuple[0]
               day=t_tuple[1]
            else:
                day = day - 1

        elif time == "三天前":
            before = 3
            if day - 3 <= 0:
                t_tuple = time_data(year, month, day,before)
                month = t_tuple[0]
                day = t_tuple[1]
            else:
                day = day - 3

        elif time == "七天前":
            before=7
            if day - 7 <= 0:
                t_tuple = time_data(year, month, day,before)
                month = t_tuple[0]
                day = t_tuple[1]
            else:
                day = day - 7
        elif time == "本月":
            day = 1
    return year, month, day



# post请求返回值计算
def post_attendance(time, state, department, emp):
    # 调用计算显示多少号之前数据的方法
    time_date = time_calculate(time)
    # 查看输入的用户Id是否存在
    if emp != '':
        try:
            emp_obj = Employee.objects.get(emp_id=emp)
        except:
            return {'code': 30100, 'error': "用户编号输入有误!"}
    # 查看要查找的状态当返回值为'全部'时查找全部的状态,不为全部时查找对应的状态数据
    if state == '全部':
        atts = Overtime.objects.filter(
            start_time__gt=datetime.datetime(time_date[0], time_date[1], time_date[2]))
    else:
        atts = Overtime.objects.filter(
            start_time__gt=datetime.datetime(time_date[0], time_date[1], time_date[2]),
            state=state)
    att_list = []
    for att in atts:
        # 获取数据库中查询到的用户id与客户输入id进行比较
        emp_id = att.emp_id.emp_id
        if emp != "":
            if emp_id != emp:
                continue
        # 获取数据库中查询到的部门与客户选择的部门进行比较
        dep = att.emp_id.dep_id.dep_name
        if department != "全部":
            if dep != department:
                continue
        # 获取相应的数据(员工姓名,上线时间,下线时间,状态)
        name = att.emp_id.name
        start_time = att.start_time
        end_time = att.end_time
        state = att.state
        att_dict = {}
        att_dict['emp_id'] = emp_id
        att_dict['name'] = name
        att_dict['dep'] = dep
        att_dict['start_time'] = start_time.strftime('%Y-%m-%d %H:%M:%S')
        att_dict['end_time'] = end_time.strftime('%Y-%m-%d %H:%M:%S')
        att_dict['state'] = state
        att_list.append(att_dict)
    return {'code': 200, 'att': att_list}


class AttendanceView(View):
    # get 请求的请求函数
    def get(self, request):
        att_list = get_attendance()
        return JsonResponse({'code': 200, 'att': att_list})

    # post 请求的请求函数
    def post(self, request):
        json_str = request.body
        py_obj = json.loads(json_str)
        # 获取到前端选择的(时间范围,状态,部门,用户)的值
        time = py_obj['time']
        state = py_obj['state']
        department = py_obj['department']
        dep_id = py_obj['dep_id']
        # 调用post请求返回值计算的方法
        att_list = post_attendance(time, state, department, dep_id)
        return JsonResponse(att_list)





# 导出的类,没有写完对其他功能没影响
class AttendanceExportView(View):
    def post(self,request):
        json_str=request.body
        py_obj=json.loads(json_str)
        # print(py_obj['emp_id'],
        #       py_obj["name"],
        #       py_obj["dep"],
        #       py_obj["start_time"],
        #       py_obj["end_time"],
        #       py_obj["state"]
        #       )
        print(111111111)
        print(py_obj)
        print(2222222222)
        return JsonResponse({"code":200})
        # py_obj['emp_id']
        # py_obj["name"]
        # py_obj["dep"]
        # py_obj["start_time"]
        # py_obj["end_time"]
        # py_obj["state"]
